/*
 * All rights Reserved, Designed By Rylynn
 * @ClassName:  ClusterListener
 * @Description:
 * @author: rylynn
 * @date:   2021/7/11
 *
 */

package org.etnetwork.distributed;

import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedAbstractActor;
import akka.cluster.Cluster;
import akka.cluster.ClusterEvent;
import akka.cluster.ClusterEvent.*;

public class ClusterListener extends UntypedAbstractActor {
    Cluster cluster = Cluster.get(getContext().system());

    @Override
    public void preStart() throws Exception {
        cluster.subscribe(getSelf(), (SubscriptionInitialStateMode) ClusterEvent.initialStateAsEvents(),
                MemberEvent.class, UnreachableMember.class);
    }

    @Override
    public void postStop() throws Exception {
        cluster.unsubscribe(getSelf());
        super.postStop();
    }

    @Override
    public void onReceive(Object message) throws Throwable, Throwable {
        if (message instanceof ClusterEvent.MemberUp) {
            MemberUp memberUp = (MemberUp) message;
            System.out.println(memberUp.member());
        } else if (message instanceof UnreachableMember) {
            UnreachableMember unreachableMember = (UnreachableMember) message;
            System.out.println(unreachableMember.member());
        } else if (message instanceof MemberRemoved) {
            MemberRemoved memberRemoved = (MemberRemoved) message;
            System.out.println(memberRemoved.member());
        } else if (message instanceof MemberEvent) {

        } else {
            unhandled(message);
        }
    }

    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create("akkaClusterTest");
        system.actorOf(Props.create(ClusterListener.class));
    }
}
